package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/employee")
public class EmployController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request){
        //      1、获取用户名+密码 ：User对象接收数据
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername,employee.getUsername());//   4、比对成功，说明用户名是对的。
        Employee emp = employeeService.getOne(qw);
        if(emp == null || StringUtils.isEmpty(employee.getUsername()) || StringUtils.isEmpty(employee.getPassword())){
            return R.error("登录错误,请输入正确的用户名和密码");// 判断：查询不到，返回登录失败
        }
        request.getSession().setAttribute("employeeLogin",emp.getId());//​ 存用户信息【只存用户的id】到session。
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(password.equals(emp.getPassword())){// 比对成功，说明用户密码是对的。比对失败，返回登录失败
            return R.success(emp);
        }
        if(emp.getStatus() == 0){//​判断：用户是否禁用【status：0禁用  1正常】，如果是禁用，返回登录失败【员工已禁用】
            return R.error("账号已被占用");
        }
        return R.success(emp);//​ 返回响应结果
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录员工的id
       request.getSession().removeAttribute("employee");
       return R.success("退出成功");
    }

    /*
    * 添加
    * */
    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpServletRequest request){
        //0、检查数据，哪些是需要处理的
        //0.1: 密码使用默认的123456 ， 需要加密 DigestUtils.md5DigestAsHex
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        /*//0.2： status 不需要处理，数据库默认是1
        //0.3： create_time 和 update_time ,设置为当前系统时间  LocalDateTime.now()
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //0.4： create_user 和 update_user 创建人和修改人，应该是当前登陆人，从session中获取
        Long empId = (Long) request.getSession().getAttribute("employeeLogin");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);*/
        //1、调用业务层保存 employee数据
        boolean save = employeeService.save(employee);
        if (save){
            //2、返回结果R
            return R.success("添加成功");
        }else{
            return R.error("添加失败");
        }
    }

    /*
    * 员工分页查询
    * */
    @GetMapping("/page")
    public R page(int page, int pageSize, String name){
        Page<Employee> pageinfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        employeeService.page(pageinfo,qw);
        List<Employee> records = pageinfo.getRecords();
        long total = pageinfo.getTotal();
        Map data = new HashMap();
        data.put("records",records);
        data.put("total",total);
        return R.success(data);
    }

    /*
    * 根据id查询员工信息,即回显
    * */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        if (employee!=null){
            return R.success(employee);
        }
        return R.error("没有该员工的信息");
    }

    /*
    * 修改数据
    * */
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpServletRequest request){

       /* //1、修改员工数据 update_time
        employee.setUpdateTime(LocalDateTime.now());
        //2、修改员工数据 update_user 从sesion中获取员工id
        //0、从session中获取用户信息
        Long empId = (Long)request.getSession().getAttribute("employeeLogin");
        employee.setUpdateUser(empId);*/
        //3、调用业务层修改员工信息 updateById()
        boolean update = employeeService.updateById(employee);
        if (update){
            return R.success("编辑成功");
        }else {
            return R.error("修改失败");
        }
    }
}
